//
//  ListViewController.m
//  FNMenu
//
//  Created by 航汇聚科技 on 2018/9/6.
//  Copyright © 2018年 Yi Zhou. All rights reserved.
//

#import "ListViewController.h"
#import <MJRefresh/MJRefresh.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import <LYEmptyView/UIView+Empty.h>
#import "UIViewController+Empty.h"
#import "NSDictionary+Safety.h"
#import "NSArray+Safety.h"
#import "ListTableViewCell.h"
#import "DetailViewController.h"
#import "NetManager.h"
#import "User.h"
@interface ListViewController ()<UITableViewDataSource, UITableViewDelegate>
{
    NSInteger pageNumber;
    NSInteger rowNumber;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *kindList;
@property (nonatomic, strong) NSMutableArray *needLoadCellArray;

@end

@implementation ListViewController

#pragma mark - lifeCycle
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    pageNumber = 1;
    rowNumber = 10; // 10 - 30
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self fetchDataIsHeaderRefresh:YES];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self fetchDataIsHeaderRefresh:NO];
    }];
    //设置空内容占位图
    self.tableView.ly_emptyView = [self emptyViewLoadDataBlock:^{
        [self fetchDataIsHeaderRefresh:YES];
    }];
    self.tableView.tableFooterView = [UIView new];
    self.automaticallyAdjustsScrollViewInsets = NO;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_cID) {
        [self fecthDataIsHeaderRefresh:YES];
    }
    if (_searchFoodTitle) {
        [self fetchDataByFoodTitle:_searchFoodTitle isHeaderRefresh:YES];
    }
}
#pragma mark - UITableViewDataSource, UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.kindList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ListCell" forIndexPath:indexPath];
    cell.foodTitleLabel.text = [[self.kindList safeObjectAtIndex:indexPath.row] safeObjectForKey:@"title"];
    cell.foodTagsLabel.text = [[self.kindList safeObjectAtIndex:indexPath.row] safeObjectForKey:@"tags"];
    cell.tags = [[self.kindList[indexPath.row] safeObjectForKey:@"tags"] componentsSeparatedByString:@";"];
    cell.foodIngredientLabel.text = [[self.kindList safeObjectAtIndex:indexPath.row] safeObjectForKey:@"ingredients"];
    cell.browserNumberLabel.text = [NSString stringWithFormat:@"%@",[[self.kindList safeObjectAtIndex:indexPath.row] safeObjectForKey:@"browse"]];
    cell.collectNumberLabel.text = [NSString stringWithFormat:@"%@",[[self.kindList safeObjectAtIndex:indexPath.row] safeObjectForKey:@"collect"]];
    [cell.foodAlbumsImgView sd_setImageWithURL:[NSURL URLWithString:[[self.kindList safeObjectAtIndex:indexPath.row] safeObjectForKey:@"albums"][0]] placeholderImage:[UIImage imageNamed:@""] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
    }];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailViewController *detailVC = [DetailViewController detailVCFromStroyBoard];
    detailVC.title = [[self.kindList safeObjectAtIndex:indexPath.row] safeObjectForKey:@"title"];
    detailVC.view.backgroundColor = [UIColor whiteColor];
    NSInteger foodID = [[[self.kindList safeObjectAtIndex:indexPath.row] safeObjectForKey:@"id"] integerValue];
    detailVC.foodID = foodID;
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/menu/details" params:@{@"id":[NSString stringWithFormat:@"%ld",(long)foodID], @"uid":[User userID]} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *foodInfo = [[[responseObject safeObjectForKey:@"result"] safeObjectForKey:@"data"] safeObjectAtIndex:0];
        detailVC.foodInfo = foodInfo;
        [self.navigationController pushViewController:detailVC animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
#pragma mark -
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    NSIndexPath *ip = [self.tableView indexPathForRowAtPoint:CGPointMake(0, targetContentOffset->y)];
    NSIndexPath *cip = [[self.tableView indexPathsForVisibleRows] firstObject];
    NSInteger skipCount = 2;
    if (labs(cip.row-ip.row)>skipCount) {
        NSLog(@"超过了 %ld", (long)skipCount);
        
    }
}
#pragma mark - public
+ (instancetype)listVCFromStroyBoard {
    return [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ListVC"];
}
#pragma mark - private
- (void)fetchDataIsHeaderRefresh:(BOOL)isHeaderRefresh {
    if (self.cID) {
        [self fecthDataIsHeaderRefresh:isHeaderRefresh];
    }
    if (self.searchFoodTitle) {
        [self fetchDataByFoodTitle:self.searchFoodTitle isHeaderRefresh:isHeaderRefresh];
    }
}
- (void)fecthDataIsHeaderRefresh:(BOOL)isHeaderRefresh {
    if (isHeaderRefresh) {
        pageNumber = 1;
    }else {
        pageNumber++;
    }
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/menu/label" params:@{@"cid":@(self.cID), @"pn":@(pageNumber), @"rn":@(rowNumber)} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self handleResponseObject:responseObject isHeaderRefresh:isHeaderRefresh];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}
- (void)fetchDataByFoodTitle:(NSString *)foodTitle isHeaderRefresh:(BOOL)isHeaderRefresh {
    if (isHeaderRefresh) {
        pageNumber = 1;
    }else {
        pageNumber++;
    }
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/menu/recipes" params:@{@"u_id":[User userID], @"menu":foodTitle, @"pn":@(pageNumber), @"rn":@(rowNumber)} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self handleResponseObject:responseObject isHeaderRefresh:isHeaderRefresh];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}
- (void)handleResponseObject:(id _Nullable)responseObject isHeaderRefresh:(BOOL)isHeaderRefresh {
    if (isHeaderRefresh) {
        self.kindList = [NSMutableArray arrayWithArray:[[responseObject safeObjectForKey:@"result"] safeObjectForKey:@"data"]];
        [self.tableView.mj_header endRefreshing];
    }else {
        [self.kindList addObjectsFromArray:[[responseObject safeObjectForKey:@"result"] safeObjectForKey:@"data"]];
        if ([[[responseObject safeObjectForKey:@"result"] safeObjectForKey:@"data"] count] != 0) {
            [self.tableView.mj_footer endRefreshing];
        }else {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }
    [self.tableView reloadData];
}
#pragma mark - setter
- (void)setCID:(NSInteger)cID {
    _cID = cID;
}
- (void)setSearchFoodTitle:(NSString *)searchFoodTitle {
    _searchFoodTitle = searchFoodTitle;
}
@end
